<?php

namespace App\Http\Controllers\Backend;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Model\Product;
use App\Model\ProductSaleDay;
use App\Model\ProductCategory;
use App\Model\ProductSaleMonth;

use Illuminate\Support\Facades\DB;

use App\Transformers\ProductSaleDayTransformer;
use App\Transformers\ProductSaleMonthTransformer;
use App\Transformers\ProductCategoryTransformer;
use App\Transformers\ProductTransformer;

class ProductController extends Controller
{
    /**
     * 统计日
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticProductDay(Request $request) {
        $bistro = $request->user('bistro');
        $date = $request->input('date');
        $products = $bistro->product()->get()->toArray();
        $product_ids = [];
        foreach ($products as $p) {
            array_push($product_ids, $p['id']);
        }
        $date_start = date('Y-m').'-01';
        $date_end = date('Y-m-d');
        $stimestamp = strtotime($date_start);
        $etimestamp = strtotime($date_end);
        // 计算日期段内有多少天
        $days = ($etimestamp-$stimestamp)/86400+1;

        // 保存每天日期
        $date = array();
        for($i=0; $i<$days; $i++){
            $date[] = date('Y-m-d', $stimestamp+(86400*$i));
        }

        $data = [];

        foreach ($product_ids as $prid) {
            $product = Product::findorfail($prid);
            $tmp = [
                'name' => $product['name'],
                'type' => 'line',
                'stack'=> '总量',
                'data' => []
            ];
            foreach ($date as $ddd) {
                $product_sale = ProductSaleDay::where('product_id', $prid)->where('date', $ddd)->first();
                if(empty($product_sale)) {
                    array_push($tmp['data'], 0);
                }else{
                    array_push($tmp['data'], $product_sale['total_amount']);
                }
            }
            array_push($data, $tmp);
        }

        $return_data = [
            'date' => $date,
            'data' => $data
        ];

        return $this->apiSuccess($return_data);
//        //本月日销量
//        $product_sale_days = ProductSaleDay::whereIn('product_id', $product_ids)->dateFrom($date_start, $date_end)->get()->toArray();
//
//        $dates = [];
//
//        foreach ($product_sale_days as $psd) {
//            if(!in_array($psd['date'], $dates)) {
//                array_push($dates, $psd['date']);
//            }
//        }
//        dd($product_sale_days);
//        $date = $request->input('date');
//        $products = $bistro->product()->get()->toArray();
//        $product_ids = [];
//        foreach ($products as $p) {
//            array_push($product_ids, $p['id']);
//        }
//        $product_sale_days = ProductSaleDay::whereIn('product_id', $product_ids)->date($date)->paginate(10);
//        $data['data'] = [
//            'product_sale_days' => $this->factalPaginator($product_sale_days, new ProductSaleDayTransformer())
//        ];
//        return $this->apiSuccess($data);
    }

    /**
     * 统计月
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function staticProductMonth(Request $request) {
        $bistro = $request->user('bistro');
        $month = $request->input('month');
        $products = $bistro->product()->get()->toArray();
        $product_ids = [];
        foreach ($products as $p) {
            array_push($product_ids, $p['id']);
        }
        $year = date('Y');
        $month = (int)date('m');
        $months = [];
        for ($i = 1; $i <= $month; $i++){
            if($i <= 9) {
                array_push($months, $year.'-0'.$i);
            }else{
                array_push($months, $year.'-'.$i);
            }
        }
        $data = [];

        foreach ($product_ids as $prid) {
            $product = Product::findorfail($prid);
            $tmp = [
                'name' => $product['name'],
                'type' => 'line',
                'stack'=> '总量',
                'data' => []
            ];
            foreach ($months as $mn) {
                $product_sale = ProductSaleMonth::where('product_id', $prid)->where('month', $mn)->first();
                if(empty($product_sale)) {
                    array_push($tmp['data'], 0);
                }else{
                    array_push($tmp['data'], $product_sale['total_amount']);
                }
            }
            array_push($data, $tmp);
        }

        $return_data = [
            'months' => $months,
            'data' => $data
        ];

        return $this->apiSuccess($return_data);
//        dd($data);

//        $product_sale_months = ProductSaleMonth::whereIn('product_id', $product_ids)->month( $month)->paginate(10);
//
//        $data['data'] = [
//            'product_sale_months' => $this->factalPaginator($product_sale_months, new ProductSaleMonthTransformer())
//        ];
//        return $this->apiSuccess($data);
    }

    /**
     * 商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request) {
        $bistro = $request->user('bistro');

        $name = $request->input('name');
        $type = $request->input('type');
        $start = $request->input('start');
        $end = $request->input('end');

        $products = Product::where('bistro_id', $bistro->id)->name($name)->typeOrder($type, $start, $end)->orderby('id', 'desc')->paginate(10);
        $data['data'] = [
            'products' => $this->factalPaginator($products, new ProductTransformer())
        ];
        return $this->apiSuccess($data);
    }

    /**
     * 创建商品
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function create(Request $request) {
        $bistro = $request->user('bistro');
        $input = $request->all();
        $validateResult = $this->validateCreateProduct($input);
        if ($validateResult["errorCode"] > 0) return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        $product = $this->_setProduct(new Product(), $input, $bistro);
        $product->save();
//        $data['data'] = [
//            'product' => $this->fractalItem($product, new ProductTransformer())
//        ];
        return $this->apiSuccess();
    }

    /**
     * 修改商品
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function edit(Request $request, $id) {
        $bistro = $request->user('bistro');
        $input = $request->all();
        $validateResult = $this->validateEditProduct($input);
        if ($validateResult["errorCode"] > 0) return $this->apiError($validateResult["message"], $validateResult["errorCode"]);
        $product = Product::findorfail($id);

        $product = $this->_setProductForSave($product, $input);
        $product->save();
//        $data['data'] = [
//            'product' => $this->fractalItem($product, new ProductTransformer())
//        ];
        return $this->apiSuccess();
    }

    /**
     * 删除商品
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete(Request $request, $id) {
        $bistro = $request->user('bistro');
        $product = Product::where('id', $id)->where('bistro_id', $bistro->id)->first();
        if(empty($product)) return $this->apiError('有问题');
        $product->delete();
        return $this->apiSuccess();
    }

    /**
     * 商品详情
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail(Request $request, $id) {
        $product = Product::findorfail($id);
        $data['data'] = [
            'product' => $this->fractalItem($product, new ProductTransformer())
        ];
        return $this->apiSuccess($data);
    }

    private function _setProductForSave($product, $input) {
        $product->img = $input['img'];
//        $product->status = $input['status'];
        $product->name = $input['name'];
        $product->discount = $input['discount'];
        $product->price = $input['price'];
        $product->description = $input['description'];
//        $product->product_category_id = $input['product_category_id'];
        return $product;
    }


    private function _setProduct($product, $input, $bistro) {
        $product->bistro_id = $bistro->id;
        $product->img = $input['img'];
//        $product->status = $input['status'];
        $product->name = $input['name'];
        $product->discount = $input['discount'];
        $product->price = $input['price'];
        $product->description = $input['description'];
        $product->sale_count = 0;
        $product->zan_number = 0;
        $product->product_category_id = $input['product_category_id'];
        return $product;
    }

    private function validateEditProduct($input) {
        $img = isset($input['img']) ? $input['img']: '';
//        $status = isset($input['status']) ? $input['status']: '';
        $name = isset($input['name']) ? $input['name']: '';
        $discount = isset($input['discount']) ? $input['discount']: '';
        $price = isset($input['price']) ? $input['price']: '';
        $description = isset($input['description']) ? $input['description']: '';


        if(empty($img)){
            return [
                "message" => "请上传图片",
                "errorCode" => 5000
            ];
        }
//
//        if(empty($status)){
//            return [
//                "message" => "请选择状态",
//                "errorCode" => 5000
//            ];
//        }

        if(empty($name)){
            return [
                "message" => "点名不得为空",
                "errorCode" => 5000
            ];
        }


        if(empty($discount)){
            return [
                "message" => "折扣价格不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($price)){
            return [
                "message" => "商品价格不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($description)){
            return [
                "message" => "商品描述不得为空",
                "errorCode" => 5000
            ];
        }

        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }

    private function validateCreateProduct($input) {
        $img = isset($input['img']) ? $input['img']: '';
//        $status = isset($input['status']) ? $input['status']: '';
        $name = isset($input['name']) ? $input['name']: '';
        $discount = isset($input['discount']) ? $input['discount']: '';
        $price = isset($input['price']) ? $input['price']: '';
        $product_category_id = isset($input['product_category_id']) ? $input['product_category_id']: '';
//        $sale_count = isset($input['sale_count']) ? $input['sale_count']: '';
//        $zan_number = isset($input['zan_number']) ? $input['zan_number']: '';
        $description = isset($input['description']) ? $input['description']: '';


        if(empty($img)){
            return [
                "message" => "请上传图片",
                "errorCode" => 5000
            ];
        }

//        if(empty($status)){
//            return [
//                "message" => "请选择状态",
//                "errorCode" => 5000
//            ];
//        }

        if(empty($name)){
            return [
                "message" => "点名不得为空",
                "errorCode" => 5000
            ];
        }


        if(empty($discount)){
            return [
                "message" => "折扣价格不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($price)){
            return [
                "message" => "商品价格不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($description)){
            return [
                "message" => "商品描述不得为空",
                "errorCode" => 5000
            ];
        }

        if(empty($product_category_id)) {
            return [
                "message" => "商品分类不得为空",
                "errorCode" => 5000
            ];
        }

        return [
            "message" => "没有错误信息",
            "errorCode" => 0
        ];

    }
}
